<?php
namespace app\admin\controller;

use app\common\model\AppointmentRich as AppointmentRichModel;
use app\common\model\HelpGetRich as HelpGetRichModel;

use app\common\component\help_to_rich\HelpToRichService;
use app\common\component\help_get_rich\HelpGetRichService;

class HelpGetRich extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();

		$this -> checkAuthorization();
	}

	public function index() {
		$resultHelpGetRich = HelpGetRichModel::alias('h_g_r')
			-> join('league_user u', 'h_g_r.user_id = u.user_id')
			-> field(
				'h_g_r.help_get_rich_id, h_g_r.order_id, h_g_r.price, h_g_r.create_time, h_g_r.status, ' .
				'u.username, u.realname, u.phone, u.bank_code'
			)
			-> order('h_g_r.status ASC, h_g_r.sort ASC')
			-> paginate(10);
		$this -> view -> assign('helpGetRichs', $resultHelpGetRich);

		$this -> view -> assign('totalAppointmentRich', AppointmentRichModel::where('status', 0) -> count());

		return $this -> view -> fetch();
	}

	public function match() {
		$helpGetRichId = $this -> request -> get('help_get_rich_id', 0, 'int');

		$getHelpGetRich = HelpGetRichModel::get(['help_get_rich_id' => $helpGetRichId]);
		if(!$getHelpGetRich || $getHelpGetRich -> getData('status') != 0) {
			echo '<meta charset="utf-8"><script>alert("提现订单不存在或已经匹配完成!");window.location.href="/shuashuale/helpGet/rich";</script>';exit;
		}
		$this -> view -> assign('helpGetRich', $getHelpGetRich);

		$findAppointmentRich = AppointmentRichModel::alias('a_r')
			-> join('league_user u', 'a_r.user_id = u.user_id')
			-> field(
				'a_r.help_appointment_rich_id, a_r.user_id, a_r.appointment_price, a_r.remaining_price, a_r.create_time, a_r.begin_time, a_r.to_num, a_r.status, ' .
				'u.username, u.realname, u.phone, u.bank_code'
			)
			-> order('a_r.status ASC, a_r.begin_time ASC')
			-> where('a_r.status = 0 AND a_r.remaining_price = ' . $getHelpGetRich -> price . ' AND a_r.user_id <> ' . $getHelpGetRich -> user_id)
			-> find();
		$this -> view -> assign('appointmentRich', $findAppointmentRich);

		return $this -> view -> fetch();
	}

	public function handleMatch() {
		$post = $this -> request -> post();
		if(!isset($post['help_appointment_rich_id'])) {
			echo '<meta charset="utf-8"><script>alert("无选择匹配订单!");window.location.href="/shuashuale/helpGet/rich";</script>';exit;
		}

		$getHelpGetRich = HelpGetRichModel::get(['help_get_rich_id' => $post['help_get_rich_id']]);
		if(!$getHelpGetRich || $getHelpGetRich -> getData('status') != 0) {
			echo '<meta charset="utf-8"><script>alert("提现订单不存在或已经匹配完成!");window.location.href="/shuashuale/helpGet/rich";</script>';exit;
		}
		$currentTime = time();

		$getAppointmentRich = AppointmentRichModel::get(['help_appointment_rich_id' => $post['help_appointment_rich_id']]);
		\think\Db::startTrans();
		try {
			$getAppointmentRich -> remaining_price = 0;
			$getAppointmentRich -> begin_time = $currentTime;
			$getAppointmentRich -> to_num += 1;
			$getAppointmentRich -> status = 1;
			if(!$getAppointmentRich -> save()) {
				throw new \Exception('预约,匹配失败');
			}

			$resultHelpToRich = (new HelpToRichService()) -> create([
				'help_get_rich_id' => $getHelpGetRich -> help_get_rich_id,
				'user_id' => $getAppointmentRich -> user_id,
				'price' => $getHelpGetRich -> price,
				'create_time' => $currentTime,
				'begin_time' => $currentTime,
				'over_time' => $currentTime + getParam('HELP_TO_RICH_OVERTIME') * 60 * 60,
				'status' => 1
			]);
			if($resultHelpToRich['code'] != 0) {
				throw new \Exception('打款,匹配失败');
			}

			$getHelpGetRich -> status = 1;
			$getHelpGetRich -> begin_time = $currentTime;
			$getHelpGetRich -> help_to_rich_id = $resultHelpToRich['data']['help_to_rich'] -> help_to_rich_id;
			if(!$getHelpGetRich -> save()) {
				throw new \Exception('提现,个别订单匹配失败');
			}

			$getUserHelpTo = \app\common\component\user\UserModel::get(['user_id' => $getAppointmentRich -> user_id]);
			winicSMS($getUserHelpTo -> phone, ['name' => $getUserHelpTo -> realname], 20);

			$getUserHelpGet = \app\common\component\user\UserModel::get(['user_id' => $getHelpGetRich -> user_id]);
			winicSMS($getUserHelpGet -> phone, ['name' => $getUserHelpGet -> realname], 10);

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '!");window.location.href="/shuashuale/helpGet/rich/match?help_get_rich_id=' . $post['help_get_rich_id'] . '";</script>';exit;
		}

		echo '<meta charset="utf-8"><script>alert("订单匹配成功!");window.location.href="/shuashuale/helpGet/rich";</script>';exit;
	}

	public function separate() {
		$helpGetRichId = $this -> request -> get('help_get_rich_id', 0, 'int');

		$getHelpGetRich = HelpGetRichModel::get(['help_get_rich_id' => $helpGetRichId]);
		if(!$getHelpGetRich || $getHelpGetRich -> price <= 0 || $getHelpGetRich -> getData('status') != 0) {
			if($getHelpGetRich -> price <= 0) {
				$getHelpGetRich -> price = 0;
				$getHelpGetRich -> status = 4;
				$getHelpGetRich -> save();
			}
			echo '<meta charset="utf-8"><script>alert("提现订单不存在或已经匹配完成!");window.location.href="/shuashuale/helpGet/rich";</script>';exit;
		}
		$this -> view -> assign('helpGetRich', $getHelpGetRich);

		return $this -> view -> fetch();
	}

	public function handleSeparate() {
		$post = $this -> request -> post();
		if($post['price'] <= 0) {
			echo '<meta charset="utf-8"><script>alert("拆单金额不能小于0!");window.location.href="/shuashuale/helpGet/rich/separate?help_get_rich_id=' . $post['help_get_rich_id'] .'";</script>';exit;
		}

		$getHelpGetRich = HelpGetRichModel::get(['help_get_rich_id' => $post['help_get_rich_id']]);
		if(!$getHelpGetRich || $getHelpGetRich -> price <= 0 || $getHelpGetRich -> getData('status') != 0) {
			if($getHelpGetRich -> price <= 0) {
				$getHelpGetRich -> price = 0;
				$getHelpGetRich -> status = 4;
				$getHelpGetRich -> save();
			}
			echo '<meta charset="utf-8"><script>alert("提现订单不存在或已经匹配完成!");window.location.href="/shuashuale/helpGet/rich";</script>';exit;
		}

		if($post['price'] > $getHelpGetRich -> price) {
			echo '<meta charset="utf-8"><script>alert("拆单金额不能大于当前订单!");window.location.href="/shuashuale/helpGet/rich/separate?help_get_rich_id=' . $post['help_get_rich_id'] .'";</script>';exit;
		}

		if(($getHelpGetRich -> price - $post['price']) == 0) {
			echo '<meta charset="utf-8"><script>alert("被拆订单不能等于0!");window.location.href="/shuashuale/helpGet/rich/separate?help_get_rich_id=' . $post['help_get_rich_id'] .'";</script>';exit;
		}

		$getHelpGetRich -> price -= $post['price'];
		$currentTime = time();

		\think\Db::startTrans();
		try {
			if(!$getHelpGetRich -> save()) {
				throw new \Exception('拆单失败, $getHelpGetRich save');
			}

			$createHelpGetRich = (new HelpGetRichService()) -> create([
				'help_to_rich_id' => 0,
				'user_id' => $getHelpGetRich -> user_id,
				'price' => $post['price'],
				'create_time' => $currentTime, 
				'begin_time' => $currentTime,
				'status' => 0,
				'sort' => 0,
			]);
	    	if($createHelpGetRich['code'] !== 0) {
	    		throw new \Exception($createHelpGetRich['message']);
	    	}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '!");window.location.href="/shuashuale/helpGet/rich/separate?help_get_rich_id=' . $post['help_get_rich_id'] .';</script>';exit;
		}

		echo '<meta charset="utf-8"><script>alert("拆单成功!");window.location.href="/shuashuale/helpGet/rich";</script>';exit;
	}
}
?>